/*
    Project:        Home Power Control
    File:           HPCServer.h
    Author:         christian@karunamusic.at
    Date:           01.2015
    Description:    The HPC Server.
 */

#ifndef HPCSERVER_H
#define HPCSERVER_H

#include <QTcpServer>
#include <QTimer>
#include <QMap>
#include "HPCSensor.h"
#include "HPCApplication.h"
#include "Database/HPCDatabase.h"
#include "HPCClientInfo.h"

class HPCServer : public HPCApplication
{
    Q_OBJECT
public:
    /** \brief Constructor with arguments from cpmmandline (main).
     */
    explicit HPCServer( int& argc, char** argv );
    /** \brief Destructor.
     */
    virtual ~HPCServer();

signals:
    void changed(QString& clName, HPCSensor* sensor, HPCValue& val );
    void alarmed(QString& clName, HPCSensor* sensor, HPCValue& val, bool bMax, unsigned int index );

public slots:
    /** \brief Run the eventloop.
     */
    void Run();

    /** \brief Receive command from cli.
     *
     * \param cmd the command.
     */
    void command( QString cmd );

    /** \brief Handle new incoming connections from hpc-clients.
     */
    void newConnection();
    /** \brief Client has disconnected.
     */
    void disconnected();
    /** \brief Number of byte sent to client.
     */
    void bytesWritten( qint64 bytes );
    /** \brief New request from a client.
     */
    void readyRead();

    void ValueChanged(HPCSensor* sensor, HPCSensorValue& val);
    void ValueAlarmed(HPCSensor* sensor, HPCSensorValue& val, bool bMax, unsigned int index);

protected:
    /** \brief Read configuration from .ini file.
     */
    virtual void readConfig();
    /** \brief Called if help from cli is requested.
     *
     * \param topic Helptopic or empty string for general help.
     */
    virtual void cliHelp( QString topic = "" );
    void createClients (QDomDocument doc);

private slots:
    void writeAverageValues();

private:
    QString clientNameFromSocket( QTcpSocket *cl );
    QTcpServer  *m_Server;
    HPCDatabase *m_HPCDb;
    QMap<QString,HPCClientInfo*> m_Clients;
    QTimer * m_WriteTimer;

    struct sSum {
        double dSum;
        int    Count;
    };
    QMap<uint,sSum> m_AverageValues;
};

QDataStream& operator<< ( QDataStream& os, QMap<QString,HPCSensor*>& smap );

#endif // HPCSERVER_H
